package com.ao.andou.common;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import net.oauth.OAuthServiceProvider;
import net.oauth.client.OAuthClient;
import net.oauth.client.httpclient4.HttpClient4;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;

import com.ao.andou.AppConstant;

/**
 * 
 * @author Andrew Wang
 * @version 1.0.0
 */
public final class OauthHelper {
    
    // 获取未授权的Request Token 
    private static final String REQUEST_URL = "http://www.douban.com/service/auth/request_token";
    // 请求用户授权Request Token 
    private static final String AUTHORI_URL = "http://www.douban.com/service/auth/authorize";
    // 使用授权后的Request Token换取Access Token 
    private static final String ACCESS_URL = "http://www.douban.com/service/auth/access_token";
    // 回调URI
    private static final String CALLBACK_URI = "andou:///callback";
    // access token
    public final static String ACCESS_TOKEN = "access_token";
    
    /*
     * Process Flow
     * 1 -- 
     *   check current mobile whether have user authorization.
     *   the access_token was fetched from database.
     * 2 -- 
     *   yes --> go to step 3 directly
     *   no  --> do authorization work flow.
     *   
     *   Authorization Flow
     *   1 get the request token which need to be authorized
     *   2 open the web browser, let user do authorization and get the request token 
     *     which has been authorized
     *   3 exchange the request token which got from step 2 for access token
     * 
     * 3 --
     *   create the OAuthAccessor object with valid access_token
     * 4 --
     *   save the OAuthAccessor for further use
     */
    private static OAuthAccessor oauthAccessor = createOAuthAccessor();
    
    private static OAuthAccessor createOAuthAccessor() {
        String consumerKey = AppConstant.CONSUMER_KEY;
        String callbackUrl = CALLBACK_URI;
        String consumerSecret = AppConstant.CONSUMER_SECRET;

        OAuthServiceProvider provider = new OAuthServiceProvider(REQUEST_URL, AUTHORI_URL, ACCESS_URL);
        OAuthConsumer consumer = 
            new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
        consumer.setProperty("oauth_signature_method", OAuth.HMAC_SHA1);
        return new OAuthAccessor(consumer);
    }
    
    /**
     * 
     * @throws IOException
     * @throws OAuthException
     * @throws URISyntaxException
     */
    public static void getRequestToken() throws IOException, OAuthException, URISyntaxException{
        OAuthClient client = new OAuthClient(new HttpClient4());
        client.getRequestToken(oauthAccessor);
    }
    
    public static Intent getAuthorization() throws IOException, URISyntaxException, OAuthException {
        
        String url = oauthAccessor.consumer.serviceProvider.userAuthorizationURL+
            "?oauth_token="+oauthAccessor.requestToken+
            "&oauth_callback="+oauthAccessor.consumer.callbackURL;
        
        Intent web = new Intent();
        web.setData(Uri.parse(url));
        web.setAction(Intent.ACTION_VIEW);
        return web;
    }
    
    private static String acess_token;
    public static String changeAcessToken(String request_token) throws IOException, OAuthException, URISyntaxException {
        OAuthClient client = new OAuthClient(new HttpClient4());
        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        params.add(new OAuth.Parameter("oauth_token", request_token));
        OAuthMessage message = client.invoke(oauthAccessor, "POST", ACCESS_URL, params);
        acess_token = message.getParameter("oauth_token");
        return acess_token;
    }
    
    public static void request() throws IOException, OAuthException, URISyntaxException{
        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        OAuthClient oclient = new OAuthClient(new HttpClient4());
        oauthAccessor.accessToken = acess_token;
        OAuthMessage omessage = oclient.invoke(oauthAccessor, "POST",  "", params);
    }
    
    
    public static String doOAuthGet(ArrayList<Map.Entry<String, String>> args) throws IOException, OAuthException, URISyntaxException {
        OAuthClient oAuthClient = new OAuthClient(new HttpClient4());
        OAuthMessage omessage = oAuthClient.invoke(oauthAccessor, "GET",  "", args);
        return omessage.readBodyAsString();
    }
    
    public static boolean doOAuthPost(HashMap<String, String> args) {
        
        return true;
    }
    
    private final static String PREF = "PREF";
    
    public static void saveAccessToken(Context context, String token) {
        SharedPreferences settings = context.getSharedPreferences(PREF, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(ACCESS_TOKEN, token);
        editor.commit();
    }
    
    public static String getAccessToken(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREF, 0);
        return settings.getString(ACCESS_TOKEN, null);
    }
    

}
